package com.android.androidintellectguess;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;


public class Single extends Activity {
	private static final String TAG = Utils.TAG;
	private static int digits=0;
	private String patternRegx="";
	private String gamemode=Utils.NORMAL;
	private String preferences="";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.singleplay);
		//setup FONT
		final Typeface tf = Typeface.createFromAsset(getAssets(), Utils.FONTDEFAULT);
		Utils.applyFonts(((ViewGroup)findViewById(android.R.id.content)).getChildAt(0),tf);
				
		//============SETUP=========
		// Step 1: Make OnclickListerner for all Number Button (0 -> 9)
		setButton();
		
		//Step 2
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			digits = Integer.parseInt(extras.getString("digits"));
			((TextView) findViewById(R.id.txtdigits)).setText(Utils.NUMBEROFDIGITS + ":" + digits);
			preferences = gamemode+digits;
		}
		
		//Setup HighScore based on Preferences values
		final TextView highscore = (TextView) findViewById(R.id.txtscore);
		SharedPreferences settings = getSharedPreferences(Utils.PREFS_NAME, 0);
		highscore.setText("HIGHEST SCORE: "  + settings.getString(preferences, "0"));
		highscore.setTextColor(Color.GREEN);
		
		//Step 3: generate Pattern and Hidden Number
		patternRegx = "";
		for(int i =0; i< digits; i++){
			patternRegx = patternRegx + "([0-9]?)";
		}
		final String hiddenNumber= Utils.generateNumber(digits);

		//Step 4: Make visible Chronometer + Input
		final EditText editText = (EditText) findViewById(R.id.mainedittext);
		TableLayout table1 = (TableLayout) findViewById(R.id.table1);
		TableRow row = new TableRow(Single.this);
		final Chronometer timer = new Chronometer(this);
		final TextView txttries = new TextView(Single.this);
		txttries.setText(Utils.NOOFTRIES + 0);
		txttries.setTypeface(tf);
		timer.setGravity(Gravity.RIGHT);
		timer.setTypeface(tf);
		((TableLayout) table1).addView(row);
		row.addView(txttries);
		row.addView(timer);
		timer.setBase(SystemClock.elapsedRealtime()); //sync timer with current time
		final Thread t = new Thread(new Runnable() {
			public void run() {
				timer.start();
				try {
					synchronized (this) {
						wait(100);
					}
				} catch (Exception e) {
					Log.e(TAG, "wait failed", e);
				}
			}
		});

		t.start();
		
		//Step 5: create listerner for Input
		editText.addTextChangedListener(new TextWatcher() {
			@Override
			public void afterTextChanged(Editable s) {
				Utils.removeSpecialChar(s,patternRegx);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start,
					int count, int after) {
			}

			@Override
			public void onTextChanged(CharSequence s, int start,
					int before, int count) {
			}
		});

		editText.setOnKeyListener(new OnKeyListener() {
			int numberOfTries = 0;

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
					numberOfTries++; //everytime user click Enter, number of tries will be increased.
					// Setup Layout
					TableLayout table1 = (TableLayout) findViewById(R.id.table1);
					TableRow row = new TableRow(Single.this);
					TextView txtinput = new TextView(Single.this);
					txtinput.setTypeface(tf);
					TextView txtresult = new TextView(Single.this);
					txtresult.setTypeface(tf);
					txtresult.setGravity(Gravity.RIGHT);
					String str = editText.getText().toString();
					String res="";
					if (str.length() != digits) {
						txtresult.setText(Utils.INVALID_NO);
						txtresult.setTextColor(Color.RED);
					} else {
						res = Utils.respond(str, hiddenNumber, timer, null);
						txtresult.setText(Html.fromHtml(res));
					}
					editText.setText("");
					txtinput.setText(str);
					row.addView(txtinput);
					row.addView(txtresult);
					((TableLayout) table1).addView(row);
					editText.setNextFocusDownId(R.id.mainedittext);
					txttries.setText(Utils.NOOFTRIES+ numberOfTries);
					if (res.equals(Utils.CONGRATS)){
						SharedPreferences settings = getSharedPreferences(Utils.PREFS_NAME, 0);
						boolean isNewHighScore = Utils.compareHighScore(
								settings.getString(preferences, "0"), timer.getText().toString());
						if (isNewHighScore){
							SharedPreferences.Editor editor = settings.edit();
							editor.putString(preferences, timer.getText().toString());
							editor.commit();
						}
						
						Button btn1 = new Button(Single.this);
						btn1.setText(Utils.PLAYAGAIN);
						((TableLayout) table1).addView(btn1);
						editText.setEnabled(false);
						editText.setClickable(false);
						btn1.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								finish();
							}
						});
					}
				}
				return false;
			}
			
		});
	}
	
	public void setButton(){
		final Button c1 = (Button) findViewById(R.id.btn01);
		final Button c2 = (Button) findViewById(R.id.btn02);
		final Button c3 = (Button) findViewById(R.id.btn03);
		final Button c4 = (Button) findViewById(R.id.btn04);
		final Button c5 = (Button) findViewById(R.id.btn05);
		final Button c6 = (Button) findViewById(R.id.btn06);
		final Button c7 = (Button) findViewById(R.id.btn07);
		final Button c8 = (Button) findViewById(R.id.btn08);
		final Button c9 = (Button) findViewById(R.id.btn09);
		final Button c0 = (Button) findViewById(R.id.btn00);
		Utils.changebg(c1);Utils.changebg(c2);Utils.changebg(c3);
		Utils.changebg(c4);Utils.changebg(c5);Utils.changebg(c6);
		Utils.changebg(c7);Utils.changebg(c8);Utils.changebg(c9);
		Utils.changebg(c0);
	}
	
	@Override
	public void onBackPressed() {
		Log.i(TAG, "back");
		digits = 0;
		super.onBackPressed();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(1, 1, 0, Utils.NEWGAME);
		SubMenu submenu = menu.addSubMenu(1, 2, 0, Utils.CHANGEDIGITS);
		submenu.add(1, 3, 0, "3");
		submenu.add(1, 4, 0, "4");
		submenu.add(1, 5, 0, "5");
		submenu.add(1, 6, 0, "6");
		SubMenu gamemode = menu.addSubMenu(1, 7, 0, "Game Mode");
		gamemode.add(1, 8, 0, Utils.NORMAL);
		gamemode.add(1, 9, 0, Utils.ATTACK);
		gamemode.add(1, 10, 0, Utils.SURVIVAL);
		menu.add(1, 11, 0, "Help");
		menu.add(1, 12, 0, "Pause");
		menu.add(1, 13, 0, "Quit");
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case 1:
			popup(digits);
			return true;
		case 2:
			return true;
		case 3:
			popup(3);
			return true;
		case 4:
			popup(4);
			return true;
		case 5:
			popup(5);
			return true;
		case 6:
			popup(6);
			return true;
		case 7:
			return true;
		case 8:
			popup(digits);
			return true;
		case 9:
			gamemode =Utils.ATTACK;
			popup(digits);
			return true;
		case 10:
			gamemode =Utils.SURVIVAL;
			popup(digits);
			return true;
		case 11:
			Intent intent = new Intent(this,Help.class);
			startActivity(intent);
			return true;
		case 12:
			pausa();
			return true;
		case 13:
			popup(0);
			return true;
		default:
			Log.i(TAG, "wth" + item.getItemId());
			return false;
		}
	}
	
	private void popup(final int digit){
		new AlertDialog.Builder(this)
		.setMessage(Utils.MSG_LOST)
		.setPositiveButton(Utils.BUTTON_OK, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				digits = digit;
				finish();
			}
		}).setNegativeButton(Utils.BUTTON_CANCEL, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				gamemode =Utils.NORMAL;
				dialog.cancel();	
			}
		}).create().show();
	}
	
	public void pausa(){
		this.onPause();
		Intent intent = new Intent(this,Pausa.class);
		startActivity(intent);
	}
	
	@Override
	public void finish() {
		Log.i(TAG, "finish and digits = " + digits);
		Intent data = new Intent();
		data.putExtra("digits", digits + "");
		data.putExtra("gamemode", gamemode);
		setResult(RESULT_OK, data);
		super.finish();
	}
}
